/**
 * Created by ding on 2017/8/14.
 */
//太阳能故障类型
var faultType = [{"value": "0", "name": "损毁"}, {"value": "1", "name": "其他"}];
var gMap;

$.getActorId = function (data) {
    if (data.indexOf("7") >= 0) {
        actorId = 7;
    }
    if (data.indexOf("1") >= 0) {
        actorId = 1;
    }
    return actorId;
};

var actorId = $.getActorId(gUserLoginResult.userActors);


$.getOrgList = function () {
    $.ajax({
        url: "../rds_fault/getOrg4Select",
        type: "post",
        dataType: "json",
        async: false,
        data: {
            "actorId": actorId,
            "orgId": gUserLoginResult.orgId
        },
        success: function (msg) {
            if (msg != null || typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    select = "<select id='orgSelect' class='form-control' name='searchText'>" +
                        "<option val=''>全部维护单位</option>"
                    var orgData = msg.jsonData;
                    for (var i = 0; i < orgData.length; i++) {
                        var icon = "Ⅰ";
                        if (orgData[i].orgType == 0)
                            icon = "Ⅱ";
                        select += "<option val=" + orgData[i].orgId + ">" + icon + "&nbsp;" + orgData[i].orgName + "</option>";
                    }
                    select += "</select>";
                } else
                    $.alert("获取公司列表失败", 2);
            }
        }
    })
};

$.getOrgList();

var gActorId = $.getActorId(gUserLoginResult.userActors);
$(function () {
    gMainDT = $("#mainDataTables").DataTable({
        ajax: {
            url: "../rds_roadLineFaultCheck/getRoadLineFaultCheck4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTables').DataTable().search(this.value);
                d.actorId=actorId;
                d.orgId = gUserLoginResult.orgId;
            }
        },
        columns: [{
            data: "roadLineFaultId",
            targets: 0
        }, {
            data: "roadLinePhoto",
            render: function (data, type, row) {
                var pic = data.split(",");
                if (pic[0])
                    return "<img src='http://hldoss.oss-cn-hangzhou.aliyuncs.com/" + pic[0] + "' style='width: 50px; height: 40px; cursor: pointer' " +
                        "onclick='$.showPicModal(\"" + data + "\")'>";
                else
                    return "<img src='../images/default_photo.png' style='width: 50px; height: 40px; cursor: pointer'>";
            }
        },{
            data: "roadLineOrgName"
        },{
            data: "roadLineFaultCreatorName"
        },{
            data: "roadLineFaultTime",
            render: function (data, type, row, meta) {
                return data.substring(0, 10);
            }
        },{
            data: "roadLineCheckerName"
        },{
            data: "roadLineMainCheckerName",
            render: function (data, type, row) {
                if (data == null) {
                    return "暂未审核"
                }
                else {
                    return data;
                }
            }
        },{
            data: "roadLineId",
            render: function (data, type, row) {
                var allData = JSON.stringify(row).replace(/\'/g, "&apos;");
                return "<button class='btn btn-primary btn-xs btn-flat' onclick='$.solarEnergyDetails (" + allData + ")' title='标线详情'>点击查看</button>";
            }
        },{
            data: "roadLineFaultId",
            render:function (data,type,row) {
                var allData = JSON.stringify(row).replace(/\'/g, "&apos;");
                return checkButton = "<button class='btn btn-primary btn-xs btn-flat' onclick='$.solarFaultDetails (" + allData + ")' title='故障详情'>点击查看</button>";
            }
        },{
            data: "roadLineFaultId",
            render: function (data, type, row) {
                // 左侧工具栏按钮的权限
                // var buttonInsert = "<button class='btn btn-info btn-xs btn-flat' onclick='$.addFaultReport()' title='添加'><i class='fa fa-plus-square'></i></button>";
                var buttonAudit = "";
                if (gActorId == 7 || gActorId == 1 ) {
                    if (row.roadLineMainCheck == 0)
                        buttonAudit = "<button  class='btn btn-primary btn-xs btn-flat'  onclick='$.showCheckModal(" + JSON.stringify(row) + ")'><span class='glyphicon glyphicon-check' aria-hidden='true' ></span>审核</button>";
                    if (row.roadLineMainCheck == -1)
                        buttonAudit = "<button  class='btn btn-danger btn-xs btn-flat' disabled='disabled'>未通过</button>";
                    if (row.roadLineMainCheck == 1)
                        buttonAudit = "<button  class='btn btn-primary btn-xs btn-flat' disabled='disabled'>已通过</button>";
                }
                return buttonAudit;
            }
        }],
        dom: "<'row'<'col-md-4'l><'#mainToolbar.col-md-8'>r>t<'row'<'col-md-6'i><'col-md-6'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'><button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>";
            strToolBar += "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>";
            strToolBar += "<span class='caret'></span><span class='sr-only'>切换下拉</span></button><ul class='dropdown-menu'>";
            strToolBar += "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-reFaultReportesh'></i> 刷新</button></li>";
            // var buttonInsert = "<li><button href='#' class='btn btn-info btn-sm btn-flat btn-block' onclick='$.addFaultReport()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            // 下拉工具栏不处理更新事件，但今后可能需要审核等功能，替换该位置即可
            //var buttonUpdate = "<li><button href='#' class='btn btn-warning btn-sm btn-flat btn-block' onclick='$.updateFaultReport()'><i class='fa fa-edit'></i> 编辑</button></li>";
            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' onclick='$.deleteFaultReport(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            // gInsert == 0 ? strToolBar : strToolBar += buttonInsert;
            // 同上方更新事件同时处理
            //gUpdate == 0 ? strToolBar : strToolBar += buttonUpdate;
            // gDelete == 0 ? strToolBar : strToolBar += buttonDelete;
            strToolBar += "</ul></div> <div class='input-group input-group-sm'>" + select + "";
            strToolBar += "<span class='input-group-btn'><button class='btn btn-primary  btn-flat' type='button' onclick='$(this).searchDT()'><i class='fa fa-search'></i></button></span></div></div>";
            $("#mainToolbar").append(strToolBar);
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    //故障类型初始化(上报时)
    var faultTypeInit = "";
    for (var i = 0; i < faultType.length; i++) {
        faultTypeInit += "<option value='" + faultType[i].value + "'>" + faultType[i].name + "</option>";
    }
    $("#addSolarFault_solarType").append(faultTypeInit);

});

// 搜索框查询操作
$.fn.searchDT = function () {
    // 注意gSelect查询权限的处理，由该表是否存在添加人或者审核人决定
    var searchText = $("#orgSelect").find("option:selected").attr("val");
    gMainDT.search(searchText).draw();
};

$.showPicModal = function (picList) {
    dex = 0;//图片轮转置0
    picList = picList.split(",");
    var pic = $('.img-content');
    pic.html("").css("top", "0px");
    for (var i in picList) {
        if (picList[i] != "" && picList[i].indexOf("http") < 0)
            pic.append("<img src='http://hldoss.oss-cn-hangzhou.aliyuncs.com/" + picList[i] + "'>")
        else
            pic.append("<img src='" + picList[i] + "'>")
    }
    $(".img-content img[src]:first").show();
    $("#showPicList").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

/************图片轮转实现2*************************/
function next2() {
    var $imgList = $(".img-content img[src]");
    $imgList.eq(dex).hide();
    if (dex == $imgList.length - 1)
        dex = 0;
    else dex++;
    $imgList.eq(dex).fadeIn()
}

function prev2() {
    var $imgList = $(".img-content img[src]");
    $imgList.eq(dex).hide();
    if (dex == 0)
        dex = $imgList.length - 1;
    else dex--;
    $imgList.eq(dex).fadeIn()
}

var $next2=_debounce(next2, 200)
var $prev2=_debounce(prev2, 200)

$(".next2").click($next2);

$(".prev2").click($prev2);

$.showCheckModal = function (jsonData) {
    MaintenancePeopleNames = "";
    $("#addPerson").hide();
    $.ajax({
        url: "../rds_roadLineController/getCoordinatesById",
        type: "post",
        data: {
            roadLineId: jsonData.roadLineId,
            type: 1
        },
        success: function (msg) {
            if (msg != null && typeof msg != "undefined") {
                if (msg.isSuccess == true) {
                    var points = "", josnData = msg.jsonData;
                    josnData.forEach(function (value, index, array) {
                        points += value.coordinateLongitude + "," + value.coordinateLatitude + ";";
                        var url = "management/roadLineMap.html";
                        url += "?coordinate=" + points + "&type=3";//通过这种方式传参数
                        $("#showEventContent4Audit").attr("src", url);
                    });
                    $("#coordinate").val(points);
                    $("#roadLinePoints").val(points);
                }
            }
        }
    });
    $("#solarMoney4Audit").text(jsonData.roadLineMoney)
    $("#signFaultId").val(jsonData.roadLineFaultId);
    $("#signFaultCheckBack4Audit").removeAttr("readOnly");
    $("#signFaultId4Audit").html(jsonData.roadLineFaultId);
    var faultLevel;
    switch (jsonData.roadLineFaultLevel) {
        case 1:
            faultLevel = "一级";
            break;
        case 2:
            faultLevel = "二级";
            break;
        case 3:
            faultLevel = "三级";
            break;
        case 4:
            faultLevel = "四级";
            break;
        case 5:
            faultLevel = "五级";
            break;
        default:
            faultLevel = "未知";
            break;
    }
    $("#signFaultLevel4Audit").html(faultLevel);
    var faultType;
    switch (jsonData.roadLineFaultType) {
        case 0:
            faultType = "损毁";
            break;
        case 1:
            faultType = "其他";
            break;
        default:
            faultType = "未知";
            break;
    }
    $("#signFaultType4Audit").html(faultType);
    $("#checkPerson4Audit").html(jsonData.roadLineCheckerName);
    $("#signFaultPeopleName4Audit").html(jsonData.roadLineFaultCreatorName);
    $("#signFaultTime4Audit").html(jsonData.roadLineFaultTime.substring(0, 10));
    $("#signFaultReason4Audit").html(jsonData.roadLineFaultReason);
    $("#signFaultPic4Audit").attr('src', jsonData.roadLinePhoto);
    $("#preViewImg").attr('src', jsonData.roadLinePhoto);
    $("#signFaultCheckBack4Audit").val(jsonData.roadLineFeedback);
    $("#auditModalLabel").text("当前故障审核");
    $("#auditModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.showMePhoto = function () {
    if ($("#preViewImg").attr("src") != "") {
        $("#auditModal").modal("hide");
        $("#preModal").modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        });
    } else {
        $.alert("未上传故障图片", 3);
    }

};
//审核按钮
$.faultAudit =function (isPass) {
    var signFaultCheckBack = $("#signFaultCheckBack4Audit").val();
    if (signFaultCheckBack == "" && isPass == -1) {
        $.alert('请填写审核反馈', 2);
    } else if (signFaultCheckBack.length > 200) {
        $.alert("审核反馈字数不能超过200", 2);
    }  else {
        $.ajax({
            url: "../rds_roadLineFaultCheck/roadLineFaultAudit",
            type: 'post',
            async: false,
            data: {
                userDevice: 'web',
                isPass: isPass,
                feedback: signFaultCheckBack,
                faultId: $("#signFaultId").val(),
                userId:gUserLoginResult.userId
            },
            dataType: 'json',
            success: function (msg) {
                if (msg != null && typeof (msg) != "undefined") {
                    if (msg.isSuccess == true) {
                        $.alert("操作成功", 1);
                        $.closeShowModal();
                        MaintenancePeopleId = null;
                        gMainDT.ajax.reload(null, false);
                    } else
                        $.alert("操作失败！", 2);
                } else {
                    $.alert('系统错误', 2);
                }
            },
            error: function (data) {
                $.alert("系统错误", 2);
            }
        })
    }
}

// 关闭showInfoModal
$.closeShowModal = function () {
    $("#auditModal").modal("hide");
    $("#signFaultCheckBack4Audit").val("");
    gMainDT.ajax.reload(null, false);
};

//太阳能详情
$.solarEnergyDetails = function (data) {
    gMap=0;
    if (data.roadLinePhoto != "" && data.roadLinePhoto != null) {
        $("#detail_solarEnergyPhoto").attr("src", data.roadLinePhoto);
    }
    else {
        $("#detail_solarEnergyPhoto").attr("src", "../images/default_photo.png");
    }
    $.ajax({
        url: "../rds_roadLineController/getCoordinatesById",
        type: "post",
        data: {roadLineId: data.roadLineId, type: 1},
        success: function (msg) {
            console.log(msg)
            if (msg != null && typeof msg != "undefined") {
                if (msg.isSuccess == true) {
                    var points = "", josnData = msg.jsonData;
                    josnData.forEach(function (value, index, array) {
                        points += value.coordinateLongitude + "," + value.coordinateLatitude + ";";
                    });
                    console.log("detail_coordinate:",points)
                    $("#detail_coordinate").val(points);
                }
            }
        }
    });
    $.ajax({
        url: "../rds_roadLineFaultCheck/getRoadLineInfo2Fault",
        type: 'post',
        async: true,
        data: {
            userDevice: 'web',
            roadLineId: data.roadLineId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $("#detail_solarEnergyProvince").val(msg.jsonData.roadLineProvince);
                    $("#detail_solarEnergyCity").val(msg.jsonData.roadLineCity);
                    $("#detail_solarEnergyArea").val(msg.jsonData.roadLineArea);
                    // $("#detail_coordinate").val(msg.jsonData.solarEnergyLongitude + "," + msg.jsonData.solarEnergyLatitude);
                    $("#detail_solarEnergyMainOrgName").val(msg.jsonData.roadLineMainOrgName);
                    $("#detail_solarEnergyOrgName").val(msg.jsonData.roadLineOrgName);
                    $("#detail_solarEnergyCreatorName").val(msg.jsonData.roadLineCreatorName);
                    $("#detail_solarEnergyStartRoad").val(msg.jsonData.roadLineStartRoad);
                    $("#detail_solarEnergyEndRoad").val(msg.jsonData.roadLineEndRoad);
                    $("#detail_solarEnergyRoadName").val(msg.jsonData.roadLineRoadName);
                    $("#detail_solarEnergyInstallOrg").val(msg.jsonData.roadLineInstallOrg);
                    $("#detail_solarEnergyType").val(msg.jsonData.roadLineType);
                    $("#detail_roadLineGraphic").val(msg.jsonData.roadLineGraphic);
                    $("#detail_roadLinePeriod").val(msg.jsonData.roadLinePeriod+"年");

                    $("#solarEnergyInfoModalLabel").text("标线详情");
                    $("#solarEnergyInfoModal").modal({
                        backdrop: 'static',
                        keyboard: false,
                        show: true
                    });
                } else
                    $.alert("数据获取失败！", 2);
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function (data) {
            $.alert("系统错误", 2);
        }
    });
};

//故障详情
$.solarFaultDetails = function (data) {
    gMap=1;
    isAdd = false;
    $.ajax({
        url: "../rds_roadLineController/getCoordinatesById",
        type: "post",
        data: {roadLineId: data.roadLineId, type: 1},
        success: function (msg) {
            console.log(msg)
            if (msg != null && typeof msg != "undefined") {
                if (msg.isSuccess == true) {
                    var points = "", josnData = msg.jsonData;
                    josnData.forEach(function (value, index, array) {
                        points += value.coordinateLongitude + "," + value.coordinateLatitude + ";";
                    });
                    $("#fault_coordinate").val(points);
                }
            }
        }
    });
    $.ajax({
        url: "../rds_roadLineFaultCheck/getRoadLineFaultInfo2Fault",
        type: 'post',
        async: true,
        data: {
            userDevice: 'web',
            roadLineId: data.roadLineId,
            roadLineFaultId: data.roadLineFaultId
        },
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var data = msg.jsonData;
                    $("#addSolarFault_solarEnergyRoadName").text(data.roadLineRoadName);
                    $("#addSolarFault_address").text(data.roadLineProvince + "" + data.roadLineCity + ""
                        + data.roadLineArea + " " + data.roadLineRoadName + " " + data.roadLineStartRoad + "(起)--" + data.roadLineEndRoad + "(止)");
                    $("#addSolarFault_solarPhoto").attr("src", data.roadLineFaultPhoto);
                    $("#addSolarFault_solarMoney").val(data.roadLineMoney);
                    $("#addSolarFault_solarType").val(data.roadLineFaultType);
                    $("#addSolarFault_solarLevel").val(data.roadLineFaultLevel);
                    $("#addSolarFault_solarReason").val(data.roadLineFaultReason);
                    $("#addSolarFault_solarCreatorName").text(data.roadLineFaultCreatorName);
                    $("#addSolarFault_solarCreatorPhone").text(data.roadLineFaultCreatorPhone);
                    // $("#solarInfoMap").val(data.solarEnergyLongitude + "," + data.solarEnergyLatitude);
                    $("#addSolarFault_solarMoney").attr("disabled", true);
                    $("#addSolarFault_solarType").attr("disabled", true);
                    $("#addSolarFault_solarLevel").attr("disabled", true);
                    $("#addSolarFault_solarReason").attr("disabled", true);
                    $("#addfault_signBtn").hide();
                    $("#reportBtn").hide();

                    $("#addSolarFaultModalLabel").text("标线故障详情");
                    $("#addSolarFaultModal").modal({
                        backdrop: 'static',
                        keyboard: false,
                        show: true
                    });
                } else
                    $.alert("数据获取失败！", 2);
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function (data) {
            $.alert("系统错误", 2);
        }
    });
};


$(".myBtnUpdate").click(function () {
    //coordinate4Show
    if(gMap==0){
        $("#modalMapRoad").hide();
        var url = "management/roadLineMap.html";
        url += "?coordinate=" + $("#detail_coordinate").val() + "&type=3";//通过这种方式传参数
        $("#myMap").attr("src", url);
        $("#modal-map").modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        })
    }
    else {
        $("#modalMapRoad").hide();
        var url = "management/roadLineMap.html";
        url += "?coordinate=" + $("#fault_coordinate").val() + "&type=3";//通过这种方式传参数
        $("#myMap").attr("src", url);
        $("#modal-map").modal({
            backdrop: 'static',
            keyboard: false,
            show: true
        })
    }

});
